/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "stdafx.h"
#include "FileInputStream.h"

#define NS_SEEK_SET  	0
#define NS_SEEK_CUR 	1
#define NS_SEEK_END 	2

#define PR_RDONLY       0x01
#define PR_WRONLY       0x02
#define PR_RDWR         0x04
#define PR_CREATE_FILE  0x08
#define PR_APPEND       0x10
#define PR_TRUNCATE     0x20
#define PR_SYNC         0x40
#define PR_EXCL         0x80

// CFileInputStream

CFileInputStream::CFileInputStream()
{
    ATLTRACE( _T("CFileInputStream::CFileInputStream()\n") );
}

CFileInputStream::~CFileInputStream()
{
    ATLTRACE( _T("CFileInputStream::~CFileInputStream()\n") );
}

STDMETHODIMP CFileInputStream::init(ILocalFile* file, LONG ioFlags, LONG perm, LONG behaviorFlags)
{
    if (!file)
        return E_INVALIDARG;

    VARIANT_BOOL vbSafe = VARIANT_FALSE;
    RETURN_FAILED(file->GetSafe(&vbSafe))

    CComBSTR bsPath;
    RETURN_FAILED(file->get_nativePath(&bsPath))

    RETURN_FAILED(Init(bsPath, vbSafe));

    ATLASSERT(!ioFlags || (ioFlags & PR_RDONLY));
    ATLASSERT(!perm);
    ATLASSERT(!behaviorFlags);

    RETURN_HRESULT(m_file.Open(m_strPath));
}

STDMETHODIMP CFileInputStream::available(ULONGLONG* pRet)
{
    if (!pRet)
        return E_POINTER;

    RETURN_E_FAIL_ON_FALSE(m_file.IsValid())

    LARGE_INTEGER liSize = {0,0};
    RETURN_E_FAIL_ON_FALSE(m_file.GetSize(&liSize))

    LARGE_INTEGER liPos = {0,0};
    RETURN_E_FAIL_ON_FALSE(m_file.GetPosition(&liPos))

    *pRet = (liSize.QuadPart - liPos.QuadPart);

    return S_OK;
}

STDMETHODIMP CFileInputStream::close(void)
{
    m_file.Close();

    return S_OK;
}

STDMETHODIMP CFileInputStream::seek(LONG whence, LONGLONG offset)
{
    LARGE_INTEGER liOffset;
    liOffset.QuadPart = offset;
    RETURN_HRESULT(m_file.SetPointer(liOffset, whence));
}

STDMETHODIMP CFileInputStream::tell(ULONGLONG* pRet)
{
    if (!pRet)
        return E_POINTER;

    LARGE_INTEGER liPos = {0,0};
    RETURN_E_FAIL_ON_FALSE(m_file.GetPosition(&liPos))

    *pRet = liPos.QuadPart;

    return S_OK;
}

STDMETHODIMP CFileInputStream::setEOF()
{
    return E_NOTIMPL;
}

STDMETHODIMP CFileInputStream::isNonBlocking(VARIANT_BOOL* pRet)
{
    return E_NOTIMPL;
}
